package com.neuedu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import com.neuedu.config.NeueduException;
import com.neuedu.entity.UmsDoctor;
import com.neuedu.entity.UmsUser;
import com.neuedu.mapper.UmsDoctorMapper;
import com.neuedu.service.UmsDoctorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neuedu.util.JwtUtil;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 医生表 服务实现类
 * </p>
 *
 * @author 王禹
 * @since 2025-08-08
 */
@Service
public class UmsDoctorServiceImpl extends ServiceImpl<UmsDoctorMapper, UmsDoctor> implements UmsDoctorService {

    @Resource
    PasswordEncoder passwordEncoder;
    @Resource(name = "wyRedisTemplate")
    RedisTemplate<String, Object> redisTemplate;
    @Override
    public List<UmsDoctor> getRegistDoctor(Long deptId) {
        QueryWrapper<UmsDoctor> wrapper = new QueryWrapper<>();
        wrapper.eq("dept_id", deptId)
                .eq("can_register", 1)
                .eq("active", 1);
        return this.list(wrapper);
    }

    @Override
    public String login(String username, String password) {
        QueryWrapper<UmsDoctor> wrapper = new QueryWrapper<>();
        wrapper.eq("phone", username)
                .or().eq("email", username);
        UmsDoctor doctor = this.getOne(wrapper);
        if (null == doctor || !passwordEncoder.matches(password, doctor.getPassword())) {
            throw new NeueduException("用户或密码错误");
        }
        if(!doctor.getActive()) {
            throw new NeueduException("该用户已经禁用，无法登录");
        }
        String key = String.format("ums:%d:login", doctor.getId());
        redisTemplate.opsForValue().set(key, doctor, 30, TimeUnit.MINUTES);
        return JwtUtil.createToken(doctor);
    }

    @Override
    public boolean call(String message) {
        ActiveXComponent component =new ActiveXComponent("Sapi.SpVoice");
        component.setProperty("Volume", new Variant(100));
        component.setProperty("Rate", new Variant(0));
        Dispatch dispatch = component.getObject();
        Dispatch.call(dispatch, "Speak", new Variant(message));
        dispatch.safeRelease();
        return true;
    }
}
